import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Test {
    static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    //下面代码实现之字形打印二叉树
    public ArrayList<ArrayList<Integer>> Print(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        //若为空，返回空链表
        if (root == null) {
            return result;
        }
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        //flag用来判断是否翻转
        boolean flag = true;
        while (!q.isEmpty()) {
            //size用来记录每层节点的个数,从而控制循环次数
            int size = q.size();
            ArrayList<Integer> list = new ArrayList<Integer>();
            while (size != 0) {
                TreeNode cur = q.poll();
                list.add(cur.val);
                size--;
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            if (flag) {
                flag = false;
            } else {
                flag = true;
                //翻转list,使用Collections.reverse()方法
                Collections.reverse(list);
            }
            //将list加入result
            result.add(list);

        }
        return result;

    }

    public static void main(String[] args) {

    }
}




